/* global _opts */

function updateRoutes(r) {
    _opts.routes.available = r.available;
    _opts.routes.assigned = r.assigned;
    search('available');
    search('assigned');
}

$('#btn-new').click(function () {
    var $this = $(this);
    var route = $('#inp-route').val().trim();
    if (route !== '') {
        $.post($this.attr('href'), {route: route}, function (r) {
            $('#inp-route').val('').focus();
            updateRoutes(r);
        });
    }
    return false;
});

$('.btn-assign').click(function () {
    var $this = $(this);
    var target = $this.data('target');
    var routes = $('select.list[data-target="' + target + '"]').val();
    if (routes && routes.length) {
        $.post($this.attr('href'), {routes: routes}, function (r) {
            updateRoutes(r);
        });
    }
    return false;
});

$('#btn-refresh').click(function () {
    var $this = $(this);
    var $icon = $this.children('i');
    $icon.hide();
    $this.parent().addClass('spinner spinner-primary spinner-right');
    $.post($this.data('url'), function (r) {
        updateRoutes(r);
    }).always(function () {
        $this.parent().removeClass('spinner spinner-primary spinner-right');
        $icon.show();
    });
    return false;
});

$('#btn-pushtomenu').click(function () {
    var $this = $(this);
    var $icon = $this.children('i');
    $icon.hide();

    $this.addClass('spinner spinner-primary spinner-sm spinner-left');
    $.post($(this).attr('href'), function () {

    }).always(function () {
        $this.removeClass('spinner spinner-primary spinner-sm spinner-left');
        $icon.show();
    });
    return false;
});

$('.search[data-target]').keyup(function () {
    search($(this).data('target'));
});

function search(target) {
    var $list = $('select.list[data-target="' + target + '"]');
    $list.html('');
    var q = $('.search[data-target="' + target + '"]').val();
    $.each(_opts.routes[target], function (key, vls) {
        if (key.indexOf(q) >= 0) {
            $('<option>').text(key).val(vls).appendTo($list);
        }
    });
}

// initial
search('available');
search('assigned');
